package com.anne.fish.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import com.anne.fish.model.Info;
import com.anne.fish.webapp.formbean.InfoSearch;
import com.anne.fish.dao.InfoDao;
import com.anne.fish.dao.hibernate.GenericDaoHibernate;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

@Repository("infoDao")
public class InfoDaoHibernate extends GenericDaoHibernate<Info, Long> implements
		InfoDao {

	public InfoDaoHibernate() {
		super(Info.class);
	}

	public Integer getCountBySearch(InfoSearch infoSearch){
		StringBuffer hql = new StringBuffer();
		List<Object> objs = new ArrayList<Object>();
		hql.append("select count(*) ") ;
		genSql(infoSearch,hql ,objs );
		
		return this.getSearchCount(hql.toString(), objs.toArray());
	}
	
	public List<Info> findBySearch(InfoSearch infoSearch) {
		StringBuffer hql = new StringBuffer();
		List<Object> objs = new ArrayList<Object>();
		genSql(infoSearch,hql ,objs );
		
		hql.append(" order by id desc ");
		
		int pageSize = infoSearch.getPageRowPerPage();
		int pageNum = infoSearch.getPageCurrentPage();
		return this.findSearch(hql.toString(), pageSize, pageNum, objs.toArray());
	}

	private void genSql(InfoSearch infoSearch, StringBuffer hql,List<Object> args) {
		hql.append(" from Info  where 1=1 ");

		if ( infoSearch.getCatId() != null  &&  infoSearch.getCatId()!= InfoSearch.DEFAULT_VALUE_ALL_INT ) {
			hql.append(" and typeId = ? ");
			args.add(infoSearch.getCatId());
		}
		
		if ( infoSearch.getPic() != null  &&  infoSearch.getPic()!= InfoSearch.DEFAULT_VALUE_ALL_INT ) {
			hql.append(" and picFlag = ? ");
			args.add(infoSearch.getPic()== 1  ? true:false);
		}
		
		if ( infoSearch.getAreaId() != null  &&  infoSearch.getAreaId()!= InfoSearch.DEFAULT_VALUE_ALL_INT ) {
			hql.append(" and provinceId = ? ");
			args.add(infoSearch.getAreaId());
		}
		
		if (  !infoSearch.isPriceAll()) {
			hql.append(" and money >= ? and money <= ?");
			args.add(infoSearch.getLowPrice());
			args.add(infoSearch.getHighPrice());
		}
		// 2 means 全部
		if (infoSearch.getSell() != null
				&& infoSearch.getSell() != InfoSearch.DEFAULT_VALUE_ALL_INT) {
			hql.append(" and sellFlag =  ?");
			args.add(infoSearch.getSell()== 1  ? true:false );
		}
		
		if(!StringUtils.isBlank(infoSearch.getSearchWord())){
			hql.append(" and title like  '%").append(infoSearch.getSearchWord()).append("%' ");
			//query.setParameter(name,"%javaeye%");   ere a.client_name like '%"+ clientname+"%'");
			//args.add(infoSearch.getSearchWord());
		}
		
	}
}
